package com.botu.sentineldemo1.demo;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: hanzeyao
 * @Date: 2019/12/7 09:48
 * @Description:
 */
public class RtExDegradeDemo3 {

    private static final String key = "xxx";

    public static void main(String[] args) {
        initDegradeRule();
        Entry entry = null;
        while(true){
            try {
                entry = SphU.entry(key);
                double random = Math.random();
                TimeUnit.MILLISECONDS.sleep(500);
                System.out.println("=====pass=====");
  if(random>=0.1){
                    int a = 1/0;
                }

            } catch (Exception e) {
                System.out.println("-----block-----");
            }finally {
                if(entry != null){
                    entry.exit();
                }
            }
        }

    }

    private static void initDegradeRule(){
        List<DegradeRule> rules = new ArrayList<>();
        DegradeRule rule = new DegradeRule();
        rule.setResource(key);
        rule.setCount(0.1);
        rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
        rule.setTimeWindow(3);
        rules.add(rule);
        DegradeRuleManager.loadRules(rules);
    }
}
